package com.teamelite.exmgmt;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.PowerManager;
import android.util.Log;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.actionbarsherlock.app.SherlockActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.actionbarsherlock.view.SubMenu;

@SuppressLint("SimpleDateFormat")
public class cActivityDo extends SherlockActivity {
	private ArrayList<arrList> lstActivity;
	private String id_user,id_activity,datestart;
	private int id_imgtutor;
	private long hr,min,sec,r_hr,r_min,r_sec;
	PowerManager pm;
	PowerManager.WakeLock wl;

	
	TextView tvTimer;
	Timer timer = new Timer();
	
	class tTask extends TimerTask {
	     @Override
	     public void run() {
	         cActivityDo.this.runOnUiThread(new Runnable() {
	             @Override
	             public void run() {
	            	sec++;
	     	       	if (min>=60){ hr++; min=0; sec = 0; }
	     	       	if (sec>=60){ min++; sec=0; }
	     	       	tvTimer.setText(getString(R.string.TimeCount)+" "+String.format("%02d:%02d:%02d", hr, min, sec));
	             }
	         });
	     }
	}
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		setTheme(R.style.Theme_Sherlock);
		
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		// Power Manager
		pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
		wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Perform Activity");
		// Remove title bar
		// this.requestWindowFeature(Window.FEATURE_NO_TITLE);
		// Remove notification bar
		// this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
		setContentView(R.layout.activity_doactivity);
		DBHelper db = new DBHelper(this);
		this.id_activity = getIntent().getExtras().getString("id_activity");
		this.id_user = getIntent().getExtras().getString("id_pengguna");
		this.id_imgtutor = getIntent().getExtras().getInt("id_imagetutor");
		this.lstActivity = db.getCatActivity(getIntent().getExtras().getString("id_activity"));
		setTitle(lstActivity.get(0).nama_activity);
		((ImageView)findViewById(R.id.imgTutor)).setImageResource(this.id_imgtutor);
		tvTimer=(TextView)findViewById(R.id.tvTimer);
		tvTimer.setText(getString(R.string.TimeCount)+" 00:00:00");
		
		// Get System Date Untuk Start Date
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		
		datestart = sdf.format(new Date());
		//this.starttime=System.currentTimeMillis();
		this.hr=this.min=this.sec=this.r_hr=this.r_min=this.r_sec=0;
		
		wl.acquire();
        timer.schedule(new tTask(), 1000,1000);

		// Custom Layout
		//if (Build.VERSION.SDK_INT < Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
            //BitmapDrawable bg = (BitmapDrawable)getResources().getDrawable(R.drawable.bg_stripped);
            //bg.setTileModeXY(TileMode.REPEAT, TileMode.REPEAT);
            //getSupportActionBar().setBackgroundDrawable(bg);

            //BitmapDrawable bgSplit = (BitmapDrawable)getResources().getDrawable(R.drawable.bg_stripped);
            //bgSplit.setTileModeXY(TileMode.REPEAT, TileMode.REPEAT);
            //getSupportActionBar().setSplitBackgroundDrawable(bgSplit);
        //}
	}
	
	
	// Ambil Respon Dari Child Activity
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		int statCode = data.getExtras().getInt("status");
		this.r_hr = r_hr+data.getExtras().getLong("r_hr");
		this.r_min = r_min+data.getExtras().getLong("r_min");
		this.r_sec = r_sec+data.getExtras().getLong("r_sec");
		Log.d("cActivityDo", String.format("%02d:%02d:%02d", this.r_hr,this.r_min,this.r_sec));
		if (statCode==1){
			timer = new Timer();
			timer.schedule(new tTask(), 1000, 1000);
		}
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
        // Hilangkan Icon Disebelah Kiri Title
        getSupportActionBar().setDisplayShowHomeEnabled(false);
        
        menu.add("Rest")
        	.setIcon(R.drawable.device_access_alarms)
            .setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);

        SubMenu subMenu1 = menu.addSubMenu("Options");
        subMenu1.add("End Activities");
        subMenu1.add("Cancel");
        MenuItem subMenu1Item = subMenu1.getItem();
        subMenu1Item.setIcon(R.drawable.collections_view_as_list);
        subMenu1Item.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);

        return true;
    }
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
        if ("Rest".equals(item.getTitle())){
        	this.timer.cancel();
        	this.timer.purge();
        	Intent intent = new Intent(cActivityDo.this,cActivityDoTranslucent.class);
        	startActivityForResult(intent, Activity.RESULT_FIRST_USER);
        }else if ("End Activities".equals(item.getTitle())){
        	wl.release();
        	Intent intent = new Intent(cActivityDo.this,cActivityDoDone.class);
        	intent.putExtra("id_pengguna", this.id_user);
        	intent.putExtra("id_activity", this.id_activity);
        	intent.putExtra("sec", ""+this.sec);
        	intent.putExtra("min", ""+this.min);
        	intent.putExtra("hr", ""+this.hr);
        	intent.putExtra("r_sec", ""+this.r_sec);
        	intent.putExtra("r_min", ""+this.r_min);
        	intent.putExtra("r_hr", ""+this.r_hr);
        	intent.putExtra("datestart", this.datestart);
        	startActivity(intent);
        	finish();
        }else if ("Cancel".equals(item.getTitle())){
        	wl.release();
        	finish();
        }
        return true;
	}
	
	private boolean doubleBackToExitPressedOnce = false;
	private int i=0;
	private Timer t = new Timer();

	@Override
	protected void onResume() {
	    super.onResume();
	    this.doubleBackToExitPressedOnce = false;
	    this.i=0;
	}

	@Override
	public void onBackPressed() {
	    if (doubleBackToExitPressedOnce) {
	    	wl.release();
	        super.onBackPressed();
	        return;
	    }
	    this.doubleBackToExitPressedOnce = true;
	    Toast.makeText(this, "Press again to exit.", Toast.LENGTH_SHORT).show();
	    t.schedule(new onBackTask(), 0, 1000);
	}
	
	class onBackTask extends TimerTask {
	     @Override
	     public void run() {
	         cActivityDo.this.runOnUiThread(new Runnable() {
	             @Override
	             public void run() {
	            	 i++;
	            	 if(i==3){
	            		doubleBackToExitPressedOnce = false;
	            		i=0;
	                 	cancel();
	            	 }
	             }
	         });
	     }
	}
	
}
